import SelectedPageQuesList from "../component/SelectedPage/SelectedPageQuesList";
import BaseButton from "../component/BaseButton";
import {useAtom} from "jotai/index";
import {selectedIdsAtom} from "../store/atoms";
import {useLocation, useNavigate} from "react-router-dom";
import toast, {Toaster} from "react-hot-toast";
import {useEffect, useRef} from "react";
import {Question} from "../types";

function SelectedPage() {
    const inputRef = useRef<HTMLInputElement>(null);
    const [selectedIds, setSelectedIds] = useAtom(selectedIdsAtom);
    const location = useLocation();
    const navigate = useNavigate();
    const printStatus: string = location.state?.status || '';
    const printMessage: string = location.state?.message || '';
    const printPDF = () => {
        if (selectedIds.length == 0) {
            toast.error('未选择考题');
        } else {
            navigate('/print', {
                state: {
                    ids: selectedIds,
                    from: location.pathname
                }
            });
        }
    }
    const star = () => {
        const value = inputRef.current?.value.trim();
        if (selectedIds.length == 0) {
            toast.error('未选择考题');
        } else {
            if (!value) {
                toast.error('请输入试卷名');
                return;
            }
            toast.promise(
                async () => {
                    const quesList: Question[] = await window.ipcRender.invoke('ques:getSelected', {
                        ids: selectedIds,
                    });

                    const res = await window.ipcRender.invoke('star:addItem', {
                        ids: quesList.map(q => q.id),
                        name: value,
                        answers: quesList.map(q => q.answer)
                    });

                    return res;
                },
                {
                    loading: '处理中...',
                    success: '收藏成功',
                    error: (err) => `收藏失败：${err.message}`,
                }
            );
        }
    }
    useEffect(() => {
        if (printStatus === 'success') {
            toast.success('打印成功');
        } else if (printStatus === 'cancelled') {
            toast('打印已取消');
        } else if (printStatus === 'error') {
            toast.error(`打印异常：${printMessage}`)
        }
    }, [])
    return (
        <div>
            <Toaster
                reverseOrder={true}
                toastOptions={{
                    duration: 1000,
                    error: {
                        duration: 2000,
                    },
                    success: {
                        duration: 2000,
                    }
                }}
            />
            <SelectedPageQuesList className="mx-auto"/>
            <div className="sticky bottom-0 bg-white h-14 flex justify-between items-center">
                {/* 左侧组 */}
                <div className="flex space-x-2">
                    <BaseButton label='导出PDF'
                                onClick={printPDF}
                                className='text-lg btn-accent'
                    />
                    <input type="text" placeholder="输入试卷名..." ref={inputRef}
                           className="input input-warning w-40" />
                    <BaseButton label='收藏试卷'
                                onClick={star}
                                className='text-lg btn-warning'
                    />
                </div>
                {/* 右侧组 */}
                <div className="flex space-x-2">
                    <BaseButton label='清空'
                                onClick={() => setSelectedIds([])}
                                className='text-lg mr-12 btn-error'
                    />
                </div>
            </div>
        </div>
    );
}

export default SelectedPage